<?php

namespace App\Http\Controllers;

use App\Http\Model\Api\FinanceRechargeOrder;
use App\Http\Model\TopupRebateRecharge;
use App\Http\Model\User;
use App\Http\Services\ConfigServices;
use App\Http\Services\ShareDiamondServices;
use App\Http\Services\ShareSendGoodsServices;
use App\Http\Services\UserServices;
use Laravel\Lumen\Routing\Controller as BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

/*
 * 充值赠送钻石
 * */

class ExchangeController extends BaseController
{
    protected $configServices;
    private $ratio = 10;
    private $prize_ratio = 0.015;


    public function __construct()
    {
        //监听充值
        $this->configServices = new ConfigServices();
        $this->userServices = new UserServices();
    }

    public function assignAction($body)
    {
        $consumer_date =  time();
        $config = $this->configServices->getConfig(15);
        $checkDate = $this->configServices->checkConfigDate($config['topup_rebate_date'], $consumer_date);
        if (!$checkDate) {
            write_log('exchangeConsumer', 'timeError', $body);//活动时间错误
            return false;
        }
        // 首次充值随机返利
        $this->listenUserRecharge($body);// 充值
        
        return true;
    }
//
//{"order_id":21669,"order_sn":"1912020953232019120217304","user_id":28961,"rule_id":13,"diamond_amount":600
//,"price":600,"pay_type":12,"status":1,"create_timestamp":1575294803,"create_time":"2019-12-02 13:53:23","pay_tim
//estamp":1575294821,"out_trade_sn":"191202215323582205878900","u
//pdate_time":"2019-12-02 13:53:41","channel_id":"700035","pearl_amount":0,"recharge_type":0}

    public function listenUserRecharge($body)
    {
        // todo log
        write_log('exchangeConsumer', 'rechargeCallback', $body);

        $user_id = $body['user_id'] ?: 0;
        $kk_balance = $body['kk_value'] ?: 0;
        $kk_balance = abs($kk_balance);
        $kk_type = $body['kk_type'];
        if($kk_type != 6)  return false;
        $prize = $kk_balance / 10 * $this->prize_ratio;
        $prize = floor($prize);

        //发送接口请求
        $recharge = [
            'user_id' => $user_id,
            'diamond_num' => $prize,
            'msg' => '兑换活动奖励',
        ];
        $diamond_api = json_decode(curl_request(env('KK_API_HOST') . '/finance/diamond/recharge', $recharge), true);
        if ($diamond_api['code'] != 0) {
            //充值失败 销毁队列
            write_log('exchangeConsumer', 'oneUserRechargeError', json_encode($diamond_api));
            return false;
        }

        // 发送消息
        $msg_data_one['user_id'] = $user_id;
        $msg_data_one['msg'] = "兑换活动奖励 钻石* " . $prize;
        curl_request(env('KK_API_HOST') . '/msg/text', $msg_data_one);

        write_log('exchangeConsumer', '兑换活动奖励', $user_id);

        return true;
    }
}
